# -*- coding:utf-8 -*-
import os
import sys
import time
import getpass
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
try:
    import hou
except Exception as hou_ERR:
    print('testing')

try:
    import DeadlineConnect as Connect
    print('连接Deadline...')
except Exception as Connect_ERR:
    print('Connect_ERR:',Connect_ERR)
    dir_path = os.path.dirname(__file__)
    deadline_path = os.path.join(dir_path, 'Deadline_py3')
    print(deadline_path)
    sys.path.append(deadline_path)
    import DeadlineConnect as Connect


# HOST = '192.168.8.3'
# PORT = 8082
# connectionObject = Connect.DeadlineCon(HOST, PORT)
# # workers = connectionObject.Slaves.GetSlaveNames()
# # print(workers)
# # print(len(workers))
#
# workers_infos = connectionObject.Slaves.GetSlaveInfos()
# # print(workers_infos)
# for i in workers_infos:
#     Stat = i['Stat']


class ClientTable(QTableWidget):

    def __init__(self,connectionObject,client_account,client_password):
        super(ClientTable, self).__init__()
        self.connectionObject = connectionObject
        self.client_account = client_account
        self.client_password = client_password
        self.workers_status_map = {0:'Unknown',1:'Rendering',2:'Idle',3:'Offline',4:'Stalled',8:'StartingJob'}
        self.workers_status_color_map = {0: '#727a83', 1: '#57bd32', 2: '#ff57fa', 3: '#b5b5b5', 4: '#ff4324', 6: '#ffcf2e'}

        self.setShowGrid(True)
        self.horizontalHeader().setDefaultSectionSize(150)
        self.verticalHeader().setDefaultSectionSize(50)
        self.head_list = ['用户','渲染机', '状态', 'ip']
        self.setColumnCount(len(self.head_list))

        self.setHorizontalHeaderLabels(self.head_list)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.right_menu)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def init_items(self):
        self.clear()
        self.setHorizontalHeaderLabels(self.head_list)
        for r in range(self.rowCount()):
            for c in range(self.columnCount()):
                item = QTableWidgetItem()
                item.setText('')
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r, c, item)

    def set_data(self,datas):
        """
        data: [worker_data,worker_data,...,...] 以渲染机器名称为key的数据
        """
        self.data = datas
        if datas:
            rowcount = len(datas)
            self.setRowCount(rowcount)
            self.init_items()
            r = 0
            for i in datas:
                Stat = i.get('Stat',0)
                color = self.workers_status_color_map.get(Stat,'#727a83')
                status = self.workers_status_map[Stat]
                self.item(r,0).setText(i['User'])
                self.item(r,1).setText(i['Name'])
                self.item(r,2).setText(status)
                self.item(r,2).setTextColor(QColor(color))
                self.item(r, 3).setText(i['IP'])
                r += 1
            self.sortByColumn(0)



    def right_menu(self):
        menu = QMenu()
        openAction = QAction(u'打开Deadline',self)
        openAction.triggered.connect(self._open_deadline)
        menu.addAction(openAction)
        closeAction = QAction(u'关闭Deadline',self)
        closeAction.triggered.connect(self._close_deadline)
        menu.addAction(closeAction)
        updateAction = QAction(u'刷新',self)
        updateAction.triggered.connect(self._update)
        menu.addAction(updateAction)
        menu.exec_(QCursor.pos())



    def worker_cmd(self,open):

        rows = []
        select_items = self.selectedIndexes()
        # print(select_items)
        for i in select_items:
            row = i.row()
            if row not in rows:
                rows.append(row)
        print(rows)

        ip_list = []
        if rows:
            for r in rows:
                item = self.item(r,3)
                ip = item.text()
                ip_list.append(ip)

        print(ip_list)

        if ip_list:
            if open:
                for i in ip_list:
                    cmd = r'PsExec.exe \\{} -u {} -i 1  -p {} -d "C:\Program Files\Thinkbox\Deadline10\bin\deadlineslave.exe"'.format(i, self.client_account,self.client_password)
            else:
                for i in ip_list:
                    cmd = r'pskill.exe \\{} -u {}  -p {} -t deadlineslave.exe"'.format(i, self.client_account,self.client_password)

    def _open_deadline(self):
        self.worker_cmd(True)


    def _close_deadline(self):
        self.worker_cmd(False)

    def _update(self):
        client_datas = self.connectionObject.Slaves.GetSlaveInfos()
        self.set_data(client_datas)


class ClientControl(QWidget):

    def __init__(self,HOST,PORT,client_account,client_password):
        super(ClientControl, self).__init__()

        self.connectionObject = Connect.DeadlineCon(HOST, PORT)
        client_datas = self.connectionObject.Slaves.GetSlaveInfos()
        # self.client_account = client_account
        # self.client_password = client_password
        # print(client_datas)
        self.resize(680,900)
        self.setWindowTitle(u'渲染机控制')
        self.main_layout = QVBoxLayout()
        self.client_table = ClientTable(self.connectionObject,client_account,client_password)
        self.main_layout.addWidget(self.client_table)
        self.setLayout(self.main_layout)
        self.client_table.set_data(client_datas)
        

if __name__ == '__main__':
    HOST = '192.168.8.3'
    PORT = 8082
    client_account = ''
    client_password = ''
    app = QApplication(sys.argv)
    c = ClientControl(HOST,PORT,client_account,client_password)
    c.show()
    sys.exit(app.exec_())


